<template>
  <div class="customer-view">
    <div class="header">
      <a-button type="primary" @click="showAddModal">添加客户</a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="customers"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确定要删除这个客户吗？"
              @confirm="handleDelete(record)"
            >
              <a-button type="link">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @cancel="handleModalCancel"
      width="800px"
    >
      <a-form
        :model="customerForm"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="客户名称" name="name">
          <a-input v-model:value="customerForm.name" />
        </a-form-item>

        <a-form-item label="客户阶段" name="stage">
          <a-select v-model:value="customerForm.stage">
            <a-select-option value="LEAD">潜在客户</a-select-option>
            <a-select-option value="CUSTOMER">正式客户</a-select-option>
            <a-select-option value="PARTNER">合作伙伴</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="客户来源" name="source">
          <a-select v-model:value="customerForm.source">
            <a-select-option value="REFERRAL">推荐</a-select-option>
            <a-select-option value="WEBSITE">网站</a-select-option>
            <a-select-option value="SOCIAL_MEDIA">社交媒体</a-select-option>
            <a-select-option value="OTHER">其他</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="关联部门" name="departmentIds">
          <a-select
            v-model:value="customerForm.departmentIds"
            mode="multiple"
            placeholder="请选择关联部门"
            :loading="departmentsLoading"
          >
            <a-select-option
              v-for="dept in departments"
              :key="dept.id"
              :value="dept.id"
            >
              {{ dept.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="销售负责人" name="salesId">
          <a-select
            v-model:value="customerForm.salesId"
            placeholder="请选择销售负责人"
            :loading="salesLoading"
          >
            <a-select-option
              v-for="user in salesUsers"
              :key="user.id"
              :value="user.id"
            >
              {{ user.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="客服负责人" name="serviceId">
          <a-select
            v-model:value="customerForm.serviceId"
            placeholder="请选择客服负责人"
            :loading="serviceLoading"
          >
            <a-select-option
              v-for="user in serviceUsers"
              :key="user.id"
              :value="user.id"
            >
              {{ user.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>

      <template #footer>
        <a-space>
          <a-button @click="handleModalCancel">取消</a-button>
          <a-button type="primary" @click="handleModalOk" :loading="submitting">
            确定
          </a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { getCustomers, createCustomer, updateCustomer, deleteCustomer } from '@/api/customer';
import { getDepartments } from '@/api/department';
import { getUsers } from '@/api/user';
import type { User } from '@/types/user';

interface Customer {
  id: number;
  name: string;
  stage: string;
  source: string;
  departments?: { id: number }[];
  sales?: { id: number };
  service?: { id: number };
}

const loading = ref(false);
const customers = ref([]);
const modalVisible = ref(false);
const modalTitle = ref('');
const submitting = ref(false);
const formRef = ref<FormInstance>();

const departments = ref([]);
const departmentsLoading = ref(false);
const salesUsers = ref<User[]>([]);
const salesLoading = ref(false);
const serviceUsers = ref<User[]>([]);
const serviceLoading = ref(false);

const customerForm = ref({
  name: '',
  stage: undefined,
  source: undefined,
  departmentIds: [] as number[],
  salesId: undefined as number | undefined,
  serviceId: undefined as number | undefined
});

const rules = {
  name: [{ required: true, message: '请输入客户名称' }],
  stage: [{ required: true, message: '请选择客户阶段' }],
  source: [{ required: true, message: '请选择客户来源' }],
  departmentIds: [{ required: true, message: '请选择关联部门' }],
  salesId: [{ required: true, message: '请选择销售负责人' }],
  serviceId: [{ required: true, message: '请选择客服负责人' }]
};

const columns = [
  {
    title: '客户名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '客户阶段',
    dataIndex: 'stage',
    key: 'stage',
  },
  {
    title: '客户来源',
    dataIndex: 'source',
    key: 'source',
  },
  {
    title: '销售',
    dataIndex: ['sales', 'name'],
    key: 'sales',
  },
  {
    title: '操作',
    key: 'action',
  },
];

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const loadCustomers = async () => {
  loading.value = true;
  try {
    const response = await getCustomers({
      page: pagination.value.current - 1,
      size: pagination.value.pageSize,
    });
    customers.value = response.data.content;
    pagination.value.total = response.data.totalElements;
  } catch (error) {
    message.error('加载客户列表失败');
  } finally {
    loading.value = false;
  }
};

const fetchDepartments = async () => {
  departmentsLoading.value = true;
  try {
    const response = await getDepartments();
    departments.value = response.data;
  } catch (error) {
    message.error('加载部门列表失败');
  } finally {
    departmentsLoading.value = false;
  }
};

const fetchSalesUsers = async () => {
  salesLoading.value = true;
  try {
    const response = await getUsers({ role: 'SALES' });
    salesUsers.value = response.data;
  } catch (error) {
    message.error('加载销售用户列表失败');
  } finally {
    salesLoading.value = false;
  }
};

const fetchServiceUsers = async () => {
  serviceLoading.value = true;
  try {
    const response = await getUsers({ role: 'SERVICE' });
    serviceUsers.value = response.data;
  } catch (error) {
    message.error('加载客服用户列表失败');
  } finally {
    serviceLoading.value = false;
  }
};

const handleTableChange = (pag) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  loadCustomers();
};

const showAddModal = () => {
  modalTitle.value = '添加客户';
  customerForm.value = {
    name: '',
    stage: undefined,
    source: undefined,
    departmentIds: [],
    salesId: undefined,
    serviceId: undefined
  };
  modalVisible.value = true;
};

const handleEdit = (record: Customer) => {
  modalTitle.value = '编辑客户';
  customerForm.value = {
    name: record.name,
    stage: record.stage,
    source: record.source,
    departmentIds: record.departments?.map(dept => dept.id) || [],
    salesId: record.sales?.id,
    serviceId: record.service?.id
  };
  modalVisible.value = true;
};

const handleModalOk = async () => {
  try {
    await formRef.value?.validate();
    submitting.value = true;
    
    const formData = {
      ...customerForm.value,
      departments: customerForm.value.departmentIds.map(id => ({ id }))
    };
    
    if (modalTitle.value === '编辑客户') {
      await updateCustomer(customerForm.value.id, formData);
      message.success('更新客户成功');
    } else {
      await createCustomer(formData);
      message.success('添加客户成功');
    }
    
    modalVisible.value = false;
    loadCustomers();
  } catch (error) {
    if (error.errorFields) {
      message.error('请填写必填项');
    } else {
      message.error('保存客户失败');
    }
  } finally {
    submitting.value = false;
  }
};

const handleModalCancel = () => {
  modalVisible.value = false;
  customerForm.value = {
    name: '',
    stage: undefined,
    source: undefined,
    departmentIds: [],
    salesId: undefined,
    serviceId: undefined
  };
};

const handleDelete = async (record: Customer) => {
  try {
    await deleteCustomer(record.id);
    message.success('删除客户成功');
    loadCustomers();
  } catch (error) {
    message.error('删除客户失败');
  }
};

onMounted(() => {
  loadCustomers();
  fetchDepartments();
  fetchSalesUsers();
  fetchServiceUsers();
});
</script>

<style scoped>
.customer-view {
  padding: 24px;
}

.header {
  margin-bottom: 16px;
}
</style> 